var express = require('express');
var router = express.Router();
var { shopUserModel, usertagsModel } = require('../../../model/model');
/* GET home page. */
// 获取前端用户
router.get('/getqianusers', async (req, res) => {
  let from = req.query.data
  if (from != undefined) {
    let all = []
    if (from.from.nickname != '') {
      let nickname = RegExp(from.from.nickname)
      all.push({ nickname: nickname })
    }
    if (from.from.Identification_number != '') {
      let Identification_number = RegExp(from.from.Identification_number)
      all.push({ Identification_number: Identification_number })
    }
    if (from.from.phone != '') {
      let phone = RegExp(from.from.phone)
      all.push({ phone: phone })
    }
    if (from.from._id != '') {
      all.push({ _id: from.from._id })
    }
    if (from.from.sex != '请选择性别') {
      let sex = RegExp(from.from.sex)
      all.push({ sex: sex })
    }
    if (all.length > 0) {
      let data = await shopUserModel.find({ $and: all })
      console.log(data);
      res.send({
        data: data
      })
    }
  } else {
    let data = await shopUserModel.find()
    res.send({
      data: data
    })
  }
})

// 单个修改用户状态
router.post('/updateqianusers', async (req, res) => {
  let _id = req.body.data._id
  let type = req.body.data.type
  if (type == '有效') {
    await shopUserModel.updateOne({ _id: _id }, { user_type: false })
    res.send({
      code: 200
    })
  } else {
    await shopUserModel.updateOne({ _id: _id }, { user_type: true })
    res.send({
      code: 200
    })
  }
})

// 批量修改
router.post('/allupdateqianusers', async (req, res) => {
  let _id = req.body.data.list_id
  let type = req.body.data.item
  console.log(type);
  if (type == '有效') {
    await shopUserModel.updateMany({ _id: { $in: _id } }, { user_type: true })
    res.send({
      code: 200
    })
  } else {
    await shopUserModel.updateMany({ _id: { $in: _id } }, { user_type: false })
    res.send({
      code: 200
    })
  }
})

// 查找用户标签
router.get('/getuserlabel', async (req, res) => {
  let item = req.query.data
  if (item != undefined) {
    let name = RegExp(item.item)
    let data = await usertagsModel.find({ name: name })
    res.send({
      code: 200,
      data: data
    })
  } else {
    let data = await usertagsModel.find()
    res.send({
      code: 200,
      data: data
    })
  }

})

// 添加用户标签
router.post('/adduserlabel', async (req, res) => {
  let item = req.body.data.from
  console.log(item);
  await usertagsModel.create(item)
  res.send({
    code: 200
  })
})

// 修改用户标签
router.post('/updateuserlabel', async (req, res) => {
  let item = req.body.data.from
  if(item.tagstype == '已启用'){
    item.tagstype = true
    await usertagsModel.updateOne({ _id: item._id }, item)
    res.send({
      code: 200
    })
  }else{
    item.tagstype = false
    await usertagsModel.updateOne({ _id: item._id }, item)
    res.send({
      code: 200
    })
  }

})



module.exports = router;
